﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Petaframe.DataAccess
{

    /// <summary>
    /// Veritabanı için select komutunu oluşturur.
    /// </summary>
    internal class  UpdateCommandBuilder: CommandStringBuilderBase, ICommandStringBuilder
    {
             

        public ICommandStringBuilder CommandString(string text)
        {
            _sqlQuery.Append(text);
            return this;
        }

        public ICommandStringBuilder CommandString(TableInfo table)
        {
            if (!table.HasPrimaryKey)
                throw new InvalidOperationException("Tabloda primarykey olmadan update işlemi yapılamaz!!!");

            _sqlQuery.AppendFormat("update {0} set ", table.TableName);

            StringBuilder wherePart = new StringBuilder(" where ");

            bool commaNeeded = false;
            bool andNeeded = false;
           

            foreach (var item in table.Properties)
            {
                if (!item.PrimaryKey)
                {
                    if (commaNeeded)
                        _sqlQuery.Append(StringTools.CommaSpace);                 

                    _sqlQuery.AppendFormat("{0}={1}", item.PropertyName,item.ParameterInfo.DatabaseParameter.ParameterName);
                    commaNeeded = true;

                }
                else
                {

                    if (andNeeded)
                        wherePart.Append(" and ");

                    wherePart.AppendFormat("{0}={1}", item.PropertyName, item.ParameterInfo.DatabaseParameter.ParameterName);
                    andNeeded = true;
                }
               
            }

            _sqlQuery.Append(wherePart);

            return this;
        }


        /// <summary>
        /// Oluşturulan sql komutunu döndürür.
        /// </summary>
        /// <returns>Sql command string</returns>
        public string ToSqlCommandString()
        {
            return _sqlQuery.ToString();
        }
    }
}
